# encoding: utf-8
import datetime
import os
import socket
import time
from pprint import pprint
import socks
from TikTokApi import TikTokApi
from MyDB import MySqliteDB
from MySqlTables import TikTokVideo
import pandas as pd


db = MySqliteDB()
# socks.set_default_proxy(socks.SOCKS5, "127.0.0.1", 1080)
# socket.socket = socks.socksocket
verifyFp="verify_kmssorhs_zRFBv3yy_YT5L_4vDt_992E_XPskPqsWZyXe"
tk = TikTokApi()

while(True):
    try:
        # api = tk.get_instance(custom_verifyFp=verifyFp, use_test_endpoints=True, proxy='socks5://127.0.0.1:1080')
        api = tk.get_instance(custom_verifyFp=verifyFp, use_test_endpoints=True)
        print('get instance done, start get trending')
        hashtag = 'dog'
        # tk.by_username(hashtag)
        video_list = tk.trending(count=10)
        # video_list = tk.trending(count=100)
        # pprint(video_list)
        print('get video list done, start downloading')
        dt = datetime.datetime.now().strftime('%y%m%d')
        new_dir = os.path.join('download_video',dt)
        if not os.path.exists(new_dir):
            os.mkdir(new_dir)
        for data in video_list:
            vid = data['id']
            # if data['stats']['diggCount'] < 100000:
            #     print('ignore video {}: stats diggCount is {} < 100000'.format(vid, data['stats']['diggCount']))
            #     continue
            # elif data['stats']['playCount'] < 1000000:
            #     print('ignore video {}: stats playCount is {} < 1000000'.format(vid, data['stats']['playCount']))
            #     continue
            try:
                res = db.session.query(TikTokVideo).filter(TikTokVideo.vid == vid).all()
                if res:
                    print('video already exists: {}'.format(vid))
                    continue
            except Exception as err:
                print(err)
                continue
            dt = datetime.datetime.strptime(time.ctime(data['createTime']), "%a %b %d %H:%M:%S %Y")
            add_time = datetime.datetime.now()
            # print(dt)
            record = TikTokVideo()
            record.createTime = dt
            record.desc = data['desc']
            record.isAd = data['isAd']
            record.vid = data['id']
            record.commentCount = data['stats']['commentCount']
            record.diggCount = data['stats']['diggCount']
            record.playCount = data['stats']['playCount']
            record.shareCount = data['stats']['shareCount']
            record.downloadAddr = data['video']['downloadAddr']
            record.playAddr = data['video']['playAddr']
            record.ratio = data['video']['ratio']
            record.add_time = add_time
            print('start downloading video: {}'.format(vid))
            video_bytes = tk.get_video_by_download_url(data['video']['downloadAddr'])
            # video_bytes = tk.get_video_no_watermark(data['video']['downloadAddr'])
            file_path = "G:\\video\\{}\\tiktok-{}.mp4".format(new_dir, vid)
            with open(file_path, 'wb') as output:
                output.write(video_bytes)
            record.filePath = file_path
            db.session.add(record)
            db.session.commit()
            print('success download video {}:{}'.format(vid, file_path))
            # db.session.close()
    except Exception as err:
        print(err)
    time.sleep(10)

